from collections import deque


class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def rangeSumBST(root, low, high):
    res = 0
    q = deque()
    q.append(root)
    while len(q) > 0:
        size = len(q)
        # 每一层
        while size > 0:
            cur = q.pop()
            if cur.val >= low and cur.val <= high:
                res += cur.val
            if cur.left:
                q.append(cur.left)
            if cur.right:
                q.append(cur.right)
            size -= 1
    return res


root = TreeNode(10)
root.left = TreeNode(5)
root.right = TreeNode(15)
root.right.right = TreeNode(18)
root.left.left = TreeNode(3)
root.left.right = TreeNode(7)
print(rangeSumBST(root, 7, 15))  # 32
